package com.changgou.util;

import com.changgou.file.pojo.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;

/***
 * 实现FastDFS文件管理
 *
 * 上传 删除 下载 文件信息获取 Storage信息获取 Tracker信息获取
 */
public class FastDFSUtil {
    static{  //加载tracker信息
        String path = new ClassPathResource("fdfs_client.conf").getPath();
        try {
            ClientGlobal.init(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //文件上传

    /***
     * 上传的文件信息封装
     * @param fastDFSFile
     */

    public static String[] upload(FastDFSFile fastDFSFile) throws IOException, MyException {

        //附加参数
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author",fastDFSFile.getAuthor());
        TrackerServer trackerServer = getTrackerServer();
        //通过TrackerServer的连接信息可以获取Storage的连接信息，创建StorageClient对象存储storage的连接信息
StorageClient storageClient = new StorageClient(trackerServer,null);
        //通过StorageClient访问StorageServer，实现文件上传，并且获取文件上传后的存储信息
        String[] uploads = storageClient.upload_file(fastDFSFile.getContent(),fastDFSFile.getExt(),meta_list);
        //uploads[0]文件上传所存储到Storage上的组名字（group1）；uploads[1]文件存储到Storage上的文件名字（M00/00/00/wKjIgF6_9p6AQ7KeAACEVCdLYRA332.jpg）
        //注意，是没有/的哦！
        return uploads;
    }

    /***
     * 获取文件信息
     * @param groupName : 文件的组名
     * @param remoteFileName : 文件的存储名字
     */
    public static FileInfo getFile(String groupName,String remoteFileName) throws IOException, MyException {
        TrackerServer trackerServer = getTrackerServer();
        //通过TrackerServer获取Storage信息，创建StorageClient对象存储storage的连接信息
        //storageServer连接信息已经包含在了trackerServer当中
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //获取文件信息
         return storageClient.get_file_info(groupName, remoteFileName);
    }

    /***
     * 文件下载
     * @param groupName : 文件的组名
     * @param remoteFileName : 文件的存储名字
     */
    public static InputStream downFlie(String groupName, String remoteFileName) throws IOException, MyException {
        TrackerServer trackerServer = getTrackerServer();
        //通过TrackerServer的连接信息可以获取Storage的连接信息，创建StorageClient对象存储storage的连接信息
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //文件下载
        byte[] buffer = storageClient.download_file(groupName, remoteFileName);
        return new ByteArrayInputStream(buffer);
    }

    /***
     * 删除文件实现
     * @param group
     * @param remoteFile
     * @throws IOException
     */
    public static int deleteFile(String group,String remoteFile) throws IOException, MyException {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer,null);
        return storageClient.delete_file(group,remoteFile);
    }

    /***
     * 获取Storage信息
     */
    public static StorageServer getStorage() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getStoreStorage(trackerServer);
    }

    /**
     * 获取Strage的ip和端口信息
     */
    public static ServerInfo[] getServerInfo(String groupName, String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer,groupName,remoteFileName);
    }

    /***
     * 获取tracker信息
     */
    public static String getTrackerInfo() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        //ip和端口
        int g_tracker_http_port = ClientGlobal.getG_tracker_http_port();
        String ip = trackerServer.getInetSocketAddress().getHostString();
        return "http://"+ip+":"+g_tracker_http_port;
    }

    public static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getConnection();

    }


    public static void main(String[] args) throws IOException, MyException {
      /*  FileInfo fileInfo = getFile("group1", "M00/00/00/wKjIgF6_9p6AQ7KeAACEVCdLYRA332.jpg");
        System.out.println(fileInfo.getSourceIpAddr()+"===="+fileInfo.getFileSize());*/
      //文件下载
        //得到文件的字节输入流
        /*InputStream is = downFlie("group1", "M00/00/00/wKjIgF6_9p6AQ7KeAACEVCdLYRA332.jpg");
//写入本地磁盘
        FileOutputStream os = new FileOutputStream("F:/1.jpg");
        //定义字节缓冲区；byte（字节），意思是可以存储1024个字节类型的值。相当于批量存储字节，1024多了浪费，少了就再跑一次循环
        byte[] buffer = new byte[1024];
        //0就是原样子,判断is的长度
        while (is.read(buffer) != -1){
os.write(buffer); //写入缓冲区数据到流
        }
        os.flush();  //刷新流文件
        os.close(); //关闭文件输出流
        is.close(); //关闭输入流*/

       // System.out.println("删除文件实现(返回int值):"+deleteFile("group1", "M00/00/00/wKjIgF7BBhSANf2UAACEVCdLYRA121.jpg"));
        //获取Storage信息;println打印后换行
        //System.out.print(getStorage().getStorePathIndex()+":"+getStorage().getInetSocketAddress().getHostString());
       /* ServerInfo[] groupInfo = getServerInfo("group1", "M00/00/00/wKjIgF7BJkmAVzrvAACEVCdLYRA592.jpg");
        for(ServerInfo i : groupInfo){
            System.out.println(i.getIpAddr()+":"+i.getPort());
        }*/
        //System.out.println(getTrackerInfo());
    }
}
